import 'dart:convert';
import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:flutter_mode/zyj/net/dio_manager.dart';

class Oss {
  static Future<Response> uploadFile(File file)async{
    //验证文本域
    String policyText =
        '{"expiration": "2020-01-01T12:00:00.000Z","conditions": [["content-length-range", 0, 1048576000]]}';
    //进行utf8编码
    List<int> policyText_utf8 = utf8.encode(policyText);
    //进行base64编码
    String policy_base64 = base64.encode(policyText_utf8);
    //再次进行utf8编码
    List<int> policy = utf8.encode(policy_base64);
    String accesskey = '你的accesskey';
    //进行utf8 编码
    List<int> key = utf8.encode(accesskey);
    //通过hmac,使用sha1进行加密
    List<int> signature_pre = new Hmac(sha1, key).convert(policy).bytes;
    //最后一步，将上述所得进行base64 编码
    String signature = base64.encode(signature_pre);

    var filename = file.path.substring(file.path.lastIndexOf("/") + 1);

    FormData data = new FormData.fromMap({
      'Filename': filename,
      'key': "可以填写文件夹名（对应于oss服务中的文件夹）/" + filename,
      'policy': policy_base64,
      //'OSSAccessKeyId': accessid,
      'success_action_status': '200', //让服务端返回200，不然，默认会返回204
      'signature': signature,
      'file': /*new UploadFileInfo(file, filename)*/file
    });

    //dio的请求配置，这一步非常重要！
    Options options = new Options();
    options.responseType = ResponseType.plain;

    return DioManager.singleton.postNormal("oss的服务器地址（包含地址前缀的那一串）",data: data,options: options);
  }
}
